package com.lck.tutor.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lck.tutor.common.BaseResponse;
import com.lck.tutor.common.ErrorCode;
import com.lck.tutor.common.Result;
import com.lck.tutor.exception.BusinessException;
import com.lck.tutor.model.domain.Blog;
import com.lck.tutor.model.domain.Follow;
import com.lck.tutor.service.BlogService;
import com.lck.tutor.mapper.BlogMapper;
import com.lck.tutor.service.FollowService;
import com.lck.tutor.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author Administrator
* @description 针对表【blog】的数据库操作Service实现
* @createDate 2022-11-07 19:43:17
*/
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog>
    implements BlogService{

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private FollowService followService;

    @Override
    public BaseResponse<?> saveBlog(Blog blog,Long userId) {
        if (blog == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //保存做题笔记
        blog.setUserId(userId);
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail(ErrorCode.SYSTEM_ERROR);
        }
        //查询笔记作者的所有粉丝
        List<Follow> followList = followService.query().eq("userFollowId", userId).list();
        for (Follow follow : followList) {
            //推送到每个粉丝的收件箱中
            String key = RedisConstants.FEED_KEY + follow.getUserId();
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        return Result.success(blog.getId());
    }
}




